//
//  LSFImagePickerController.swift
//  hoonpay
//
//  Created by 李胜锋 on 2017/8/21.
//  Copyright © 2017年 lishengfeng. All rights reserved.
//

import UIKit
import AVFoundation
import Photos

typealias ImagePickerCompletion = (_ picker:UIImagePickerController, _ mediaInfo:[String:Any]?, _ image:UIImage?, _ imgData:Data?) -> Void


class LSFImagePickerController : UIImagePickerController {
    
    var completion:ImagePickerCompletion?
    var quality:CGFloat = 1.0
    var presentController:UIViewController?
    var completon:ImagePickerCompletion?
    
    
    func showActionsheet(controller:UIViewController,
                         completion:ImagePickerCompletion?,
                         quality:CGFloat = 1.0,
                         sourceView:UIView? = nil) {
        
        completon = completion
        self.quality = quality
        
        presentController = controller
        delegate = self
        self.allowsEditing = true;
        
        lsf_alert(style: .actionSheet,
                  viewController: controller,
                  actionTitles: ["拍照", "从相册中选取"],
                  cancelTitle: "取消",
                  destructiveTitle:nil,
                  sourceView: sourceView) {(title) in
                    if title == "拍照" {
                        self.openCamera()
                    }
                        
                    else if title == "从相册中选取" {
                        self.openAlbum()
                    }
        }
    }
    
    
    func openCamera() {
        if self.isCameraAvailable == false {
            lsf_alert("找不到相机")
            return
        }
        
        
        ///相机权限
        let authStatus:AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if authStatus == .denied || authStatus == .restricted {
            lsf_alert("需要获取相机权限", message:"请在“[设置]-[隐私]-[相机]”里允许使用", style: .actionSheet, viewController: self.presentController, actionTitles: ["去设置"], cancelTitle: "取消", sourceView: nil, handle: { (title) in
                if title == "去设置" {
                    let url = URL.init(string: UIApplicationOpenSettingsURLString)
                    UIApplication.shared.openURL(url!)
                }
            })
            
            return
        }
        
        
        DispatchQueue.main.async { [weak self] in
            if let strongSelf = self {
                strongSelf.sourceType = .camera
                if strongSelf.isFrontCameraAvailable {
                    strongSelf.cameraDevice = .front
                }
                strongSelf.presentController?.present(strongSelf, animated: true, completion: nil)
            }
        }
    }
    
    ///打开相册
    func openAlbum() {
        if !isPhotoLibraryAvailable {
            lsf_alert("读取相册错误")
        }
        
        
        PHPhotoLibrary.requestAuthorization { [weak self]  status in
            if status == .denied || status == .restricted {
                lsf_alert("需要获取相册权限", message:"请在“[设置]-[隐私]-[照片]”里允许使用", style: .actionSheet, actionTitles: ["去设置"], cancelTitle: "取消", sourceView: nil, handle: { (title) in
                    if title == "去设置" {
                        let url = URL.init(string: UIApplicationOpenSettingsURLString)
                        UIApplication.shared.openURL(url!)
                    }
                })
            }
            
            else if status == .authorized {
                
                DispatchQueue.main.async { [weak self] in

                    if let strongSelf = self {
                        strongSelf.delegate = strongSelf
                        strongSelf.sourceType = .photoLibrary
                        strongSelf.presentController?.present(strongSelf, animated: true, completion: nil)
                    }
                    
                }
        
            }
        }
        
    }
    
}

extension LSFImagePickerController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        var image:UIImage!
        if self.allowsEditing {
            image = info[UIImagePickerControllerEditedImage] as! UIImage
        }
        else {
            image = info[UIImagePickerControllerOriginalImage] as! UIImage
        }
        
        let data = UIImageJPEGRepresentation(image, quality)
        completon?(self, info, image, data)
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
}

extension LSFImagePickerController {
    
    ///相机权限
    func cameraPermissions() -> Bool {
        let authStatus:AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        
        if authStatus == .denied || authStatus == .restricted {
            return false
        }
        return true
    }
    
    ///相机权限
    func photoPermissions() -> Bool {
        let authStatus = PHPhotoLibrary.authorizationStatus()
        
        if authStatus == .denied || authStatus == .restricted {
            return false
        }
        return true
    }
    
    
    
    ///设备是否支持相机
    var isCameraAvailable:Bool {
        return UIImagePickerController.isSourceTypeAvailable(.camera)
    }
    
    ///设备是否支持 后置摄像头
    var isRearCameraAvailable: Bool {
        return UIImagePickerController.isCameraDeviceAvailable(.rear)
    }
    
    ///前置摄像头
    var isFrontCameraAvailable : Bool {
        return UIImagePickerController.isCameraDeviceAvailable(.front)
    }
    
    var isPhotoLibraryAvailable: Bool {
        return UIImagePickerController.isSourceTypeAvailable(.photoLibrary)
    }
    
    
    
    func cameraSupportsMesia(_ mediaType:String, sourceType:UIImagePickerControllerSourceType) -> Bool{
        if mediaType.count == 0 {
            return false
        }
        
        guard let types = UIImagePickerController.availableMediaTypes(for: sourceType) else {
            return false
        }
        
        for type in types {
            if type == mediaType {
                return true
            }
        }
        
        return false
    }
}
